package com.whfc.iot.mach.processor;

import com.whfc.common.util.JSONUtil;
import com.whfc.hdc.dto.AppDeviceFeatureDTO;
import com.whfc.hdc.service.AppDeviceService;
import com.whfc.iot.mach.constant.MsgConst;
import com.whfc.iot.mach.entity.MachMsg0x0C;
import com.whfc.iot.mach.entity.MachMsg0x8C;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description: 0x0C消息处理
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/17 9:17
 */
@Component
public class MachUpMsgProcessor0x0C implements MachUpMsgProcessor<MachMsg0x0C> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(interfaceClass = AppDeviceService.class, version = "1.0.0")
    private AppDeviceService appDeviceService;

    @Autowired
    private SessionManager sessionManager;

    @Override
    public void processMsg(MachMsg0x0C reqMsg) {

        String textMsg = JSONUtil.toString(reqMsg);
        Integer deviceId = reqMsg.getDeviceId();
        logger.info("处理0x0C数据:{}", textMsg);

        //处理硬件特征值数据
        AppDeviceFeatureDTO featureDTO = new AppDeviceFeatureDTO();
        featureDTO.setDeviceId(deviceId);
        featureDTO.setTime(reqMsg.getTime());
        featureDTO.setAccX(reqMsg.getAccX());
        featureDTO.setAccY(reqMsg.getAccY());
        featureDTO.setAccZ(reqMsg.getAccZ());
        featureDTO.setGyroX(reqMsg.getGyroX());
        featureDTO.setGyroY(reqMsg.getGyroY());
        featureDTO.setGyroZ(reqMsg.getGyroZ());
        appDeviceService.addDeviceFeature(featureDTO);


        //响应0x8C
        MachMsg0x8C resMsg = new MachMsg0x8C();
        resMsg.setStartFlag(reqMsg.getStartFlag());
        resMsg.setDeviceType(reqMsg.getDeviceType());
        resMsg.setDeviceId(reqMsg.getDeviceId());
        resMsg.setSeq(reqMsg.getSeq());
        resMsg.setResult(reqMsg.isCheckSuccess() ? MsgConst.ACK_SUCCESS : MsgConst.ACK_FAIL);
        Session session = sessionManager.getSessionByDeviceId(deviceId);
        session.getChannel().writeAndFlush(resMsg).addListener(future -> {
            logger.info("0x8C发送结果,deviceId={},isDone={},isSuccess={}", deviceId, future.isDone(), future.isSuccess());
        });
    }
}
